import numpy as np

def pagerank(transition_matrix, d=0.85, max_iterations=1000, tolerance=1e-6):
    n = transition_matrix.shape[0]
    pr = np.ones(n) / n  # 初始化每个节点的PageRank值为1/n
    for _ in range(max_iterations):
        new_pr = (1 - d) / n + d * np.dot(transition_matrix, pr)
        # 检查收敛性，若前后两次PR值变化小于阈值则停止迭代
        if np.linalg.norm(new_pr - pr) < tolerance:
            break
        pr = new_pr
    return pr




# 测试用例
transition_matrix = np.array([
    [0, 0.5, 1],   # 列表示源节点，行表示目标节点，如第一列对应源节点A的转移概率
    [1/2, 0, 0],
    [1/2, 0.5, 0]
])

result = pagerank(transition_matrix)
print("PageRank scores:", result)